package umputun.jutw.Process.to_twi;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import com.sun.syndication.feed.synd.SyndEntry;
import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.io.FeedException;
import com.sun.syndication.io.SyndFeedInput;
import com.sun.syndication.io.XmlReader;

public class RssFeed {

	private RssFeed(Builder bld) {
		this.pr = bld;
		pub_time = pr.last_pub_time;
	}

	private List<String> getNewItems() throws IllegalArgumentException, FeedException, IOException {
		List<String> result = new ArrayList<String>();
		URL feedUrl = new URL(pr.rss_url);
        SyndFeedInput input = new SyndFeedInput();
        SyndFeed feed = input.build(new XmlReader(feedUrl));

        int items_count = 0;
        for (Object e: feed.getEntries()) {
        	SyndEntry entry = (SyndEntry) e;
        	if (entry.getPublishedDate().getTime() <= pub_time)
        		break;
        	String line = entry.getTitle() + " " + entry.getLink();
        	result.add(line);
        	System.out.println(entry.getLink() + " " + entry.getPublishedDate());
        	pub_time = entry.getPublishedDate().getTime();
        	if (++items_count > pr.max_items) break;
        }
        return result;
	}

	private final Builder pr;
	private long pub_time = 0;

	public static class Builder {

		private Builder(String rss_url) {
			this.rss_url = rss_url;
		}

		public RssFeed build() {
			return new RssFeed(this);
		}


		public Builder interval(int interval_sec) {
			this.interval_sec = interval_sec;
			return this;
		}

		public Builder max_items(int max_items) {
			this.max_items = max_items;
			return this;
		}

		public Builder last_pub_time(long last_pub_time) {
			this.last_pub_time = last_pub_time;
			return this;
		}

		public Builder prefix(String prefix) {
			this.prefix = prefix;
			return this;
		}

		public Builder sufix(String sufix) {
			this.sufix = sufix;
			return this;
		}

		public Builder block_filter(String filter) {
			this.filter_mathcing = filter;
			return this;
		}

		public Builder pass_filter(String filter) {
			this.pass_only = filter;
			return this;
		}

		private final String rss_url;
		private int interval_sec = 60, max_items = 3;
		private String prefix = "", sufix="";

		private String pass_only = null;
		private String filter_mathcing = null;
		private long last_pub_time = 0;
	}


	public static void main(String[] argv) throws IllegalArgumentException, FeedException, IOException {
		Builder bld = new Builder("http://feeds.feedburner.com/Umputun");
		RssFeed rss = bld.build();
		rss.getNewItems();
	}

}
